<template>
  <div class="app-container">
    <el-container class="address-el-container">
      <el-aside width="200px" class="address-tree">
        <div class="search-type">
          <el-popover :content="allChildEmployee" width="100" placement="top-start" trigger="hover">
            <el-switch
              slot="reference"
              v-model="allChildEmployee"
              inactive-color="#13ce66"
              active-value="所有岗位"
              inactive-value="直接岗位"
              @change="switchChange"/>
          </el-popover>
        </div>
        <el-tree
          v-loading="treeLoading"
          :data="frameworkData"
          :props="defaulfProp"
          :default-expanded-keys="[frameworkData[0].id]"
          :expand-on-click-node="false"
          :allow-drag="treeNodeAllowDrag"
          :allow-drop="treeNodeAllowDrop"
          accordion
          draggable
          node-key="id"
          @node-drop="nodeDrop"
          @node-click="handleNodeClick"/>
      </el-aside>
      <el-main>
        <div class="filter-container">
          <span class="filter-container-right">
            <el-button type="primary" size="medium" icon="el-icon-plus" @click="showAddPost">新增</el-button>
            <el-button type="primary" size="medium" icon="el-icon-search" @click="showUnbindPost">未绑定</el-button>
          </span>
        </div>
        <el-table
          v-loading="postLoading"
          :data="postList"
          fit
          row-key="code"
          style="border-top: 5px solid #f2f6fc;"
          highlight-current-row
          @row-click="rowClick">
          <el-table-column align="center" label="岗位名称" prop="stext" min-width="200"/>
          <el-table-column align="center" label="对象ID" prop="objid" min-width="100"/>
          <el-table-column align="center" label="公司" prop="client" min-width="100"/>
          <el-table-column align="center" label="是否可用" min-width="100">
            <template slot-scope="scope"><span>{{ scope.row.available? '可用' : '不可用' }}</span></template>
          </el-table-column>
          <el-table-column align="center" label="来源" prop="source" min-width="80"/>
          <el-table-column align="center" label="开始日期" prop="begda" min-width="100"/>
          <el-table-column align="center" label="操作" min-width="320">
            <template slot-scope="scope">
              <div>
                <el-button v-if="bindState" type="primary" size="mini" @click.stop="addEmployeeToPost(scope.row)">添加员工</el-button>
                <span v-if="scope.row.source === 'HRSSP'" style="margin-left: 10px">
                  <el-button v-if="scope.row.available" type="danger" size="mini" @click.stop="postForbidden(scope.row)">禁用</el-button>
                  <el-button v-else type="primary" size="mini" @click.stop="postForbidden(scope.row)">激活</el-button>
                  <el-button v-if="bindState" type="warning" size="mini" @click.stop="unbindPostToOrganization(scope.row)">解绑</el-button>
                  <el-button v-else type="primary" size="mini" @click.stop="showBindPostToOrganization(scope.row)">绑定</el-button>
                  <el-button type="danger" size="mini" @click.stop="removePostToOrganization(scope.row)">删除</el-button>
                </span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
    <el-dialog :visible.sync="empVisible" center title="岗位人员信息" width="1300px">
      <el-table
        v-loading="empLoading"
        :data="employees"
        fit
        highlight-current-row>
        <el-table-column align="center" label="员工ID" prop="objid" min-width="90"/>
        <el-table-column align="center" label="名字" prop="stext" min-width="80"/>
        <el-table-column align="center" label="用户名" prop="username" min-width="80"/>
        <el-table-column align="center" label="部门" width="90">
          <template slot-scope="scope"><span>{{ scope.row.department }}</span></template>
        </el-table-column><!--用于数据驱动表格切换，不能删除-->
        <el-table-column align="center" label="邮箱" prop="email" min-width="90"/>
        <el-table-column align="center" label="手机" prop="phone" min-width="90"/>
        <el-table-column align="center" label="手机短号" prop="telephone_short" min-width="110"/>
        <el-table-column align="center" label="座机" prop="telephone" min-width="110"/>
        <el-table-column align="center" label="业务" prop="business_service1" min-width="110"/>
        <el-table-column align="center" label="证件照" prop="identification_photo" min-width="110"/>
        <el-table-column align="center" label="用工性质" prop="emp_nature" min-width="110"/>
        <el-table-column align="center" label="百分比" prop="vprozt" min-width="80"/>
        <el-table-column align="center" label="操作" prop="vprozt" min-width="80">
          <template slot-scope="scope">
            <div>
              <el-button v-if="scope.row.source === 'HRSSP'" type="warning" size="mini" @click.stop="unbindEmpFromPost(scope.row)">解绑</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog :visible.sync="FormVisible" title="新增岗位" width="600px">
      <el-form ref="ruleForm" :model="postInfo" :rules="rules" >
        <el-form-item :label-width="formLabelWidth" label="岗位名称" prop="stext">
          <el-input v-model="postInfo.stext" :style="{width: formLabelWidth}" auto-complete="off"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="岗位简称" prop="_short">
          <el-input v-model.number="postInfo._short" :style="{width: formLabelWidth}" auto-complete="off"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="开始时间" prop="begda">
          <el-date-picker
            v-model="postInfo.begda"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="开始日期时间"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="结束时间" >
          <el-date-picker
            v-model="postInfo.endda"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="结束日期时间"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="confirmPost('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="showPostVisible" title="选择绑定岗位的组织机构" width="400px">
      <el-tree
        v-loading="treeLoading"
        :data="frameworkData"
        :props="defaulfProp"
        :default-expanded-keys="[frameworkData[0].id]"
        :expand-on-click-node="false"
        accordion
        node-key="id"
        @node-click="bindPostToOrganization"/>
    </el-dialog>
    <el-dialog :visible.sync="showAddEmployeeVisible" center title="岗位添加员工" width="400px">
      <el-form ref="addEmpRef" :model="addEmployeeToPostData" :rules="employeeRules" label-position="right" label-width="80px" >
        <el-form-item label="员工" prop="objid">
          <el-select v-model="addEmployeeToPostData.objid" size="medium" placeholder="选择员工">
            <el-option v-for="item in employeesSelect" :label="item.real_name" :key="item.person_number" :value="item.person_number"/>
          </el-select>
        </el-form-item>
        <el-form-item label="百分比" prop="vprozt">
          <el-input v-model="addEmployeeToPostData.vprozt" :style="{width: formLabelWidth}" size="medium" auto-complete="off"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddEmployeeToPost('addEmpRef')">取 消</el-button>
        <el-button type="primary" @click="addEmployeeToPostConfirm('addEmpRef')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import commonApi from '@/api/commonApi'
import Sortable from 'sortablejs'
export default {
  name: 'AddressBook',
  data() {
    return {
      treeLoading: false,
      postLoading: false,
      empVisible: false,
      empLoading: false,
      FormVisible: false,
      showPostVisible: false,
      showAddEmployeeVisible: false,
      employeesSelect: [], // 选择的hrssp员工列表
      selectEmpsParams: {
        currentNo: 1,
        data: { source: 'hrssp' },
        pageSize: 10
      },
      addEmployeeToPostData: {},
      bindState: true, // 绑定状态
      postObjid: '', // 用于 绑定岗位的objid
      postInfo: {},
      rules: {
        stext: [
          { required: true, message: '请输入岗位名称', trigger: 'blur' }
        ],
        _short: [
          { required: true, message: '请输入岗位简称', trigger: 'blur' }
        ],
        begda: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ]
      },
      employeeRules: {
        vprozt: [
          { required: true, message: '请输入岗位百分比', trigger: 'blur' }
        ],
        objid: [
          { required: true, message: '请选择员工', trigger: 'change' }
        ]
      },
      formLabelWidth: '220px',
      employees: [],
      frameworkData: [{ id: null, objec: { stext: '' }}],
      allChildEmployee: '直接岗位',
      withPost: '不带岗位',
      postList: [],
      defaulfProp: {
        children: 'nodes',
        label: function(data) {
          return data.objec.stext
        }
      },
      nodeData: {},
      rowEmpData: {},
      sortable: null,
      oldList: [],
      newList: []
    }
  },
  created() {
    this.getFrameworkTree()
  },
  methods: {
    treeNodeAllowDrag(node) { // 树节点允许拖拽
      this.nodePid = node.data.pid
      return node.level > 1
    },
    treeNodeAllowDrop(nodeDraging, nodeDrop, type) { // 树节点允许存放
      if (type === ('prev' || 'next') && nodeDrop.data.pid === this.nodePid) {
        return true
      }
    },
    nodeDrop(node, nodeDrop, type, event) {
      const arrCode = nodeDrop.parent.childNodes.map(item => item.data.code)
      commonApi('/organization/sortOrganization', 'post', arrCode).then(response => {
        if (response.code === 1) {
          // this.getDirectEmployeesFromOrganization(80000008)
        }
      })
    },
    unbindEmpFromPost(row) { // 岗位与人员解绑
      this.$confirm(`确定要解绑人员 ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        commonApi('/organization/unbind', 'post', { code: row.code, pid: this.rowEmpData.code }).then(response => {
          if (response.code === 1) {
            this.$message({
              type: 'success',
              message: '解绑成功'
            })
            this.employees = this.employees.filter(item => item.code !== row.code)
          }
        })
      })
    },
    addEmployeeToPost(row) { // 显示页面添加人员
      this.showAddEmployeeVisible = true
      this.addEmployeeToPostData = {
        pid: row.code
      }
    },
    addEmployeeToPostConfirm(formName) { // 显示页面添加人员 确定
      this.$refs[formName].validate((valid) => {
        if (valid) {
          commonApi('/organization/bind', 'post', this.addEmployeeToPostData).then(response => {
            if (response.code === 1) {
              this.$message({
                type: 'success',
                message: '员工绑定成功'
              })
              this.addEmployeeToPostData.objid = null
              this.showAddEmployeeVisible = false
              this.$refs[formName].resetFields()
            }
          })
        }
      })
    },
    cancelAddEmployeeToPost(formName) { // 显示页面添加人员 取消按钮
      this.showAddEmployeeVisible = false
      this.addEmployeeToPostData.objid = null
      this.$refs[formName].resetFields()
    },
    getEmployees() { // 选择来源 hrssp的员工
      commonApi('/person/personPageList', 'post', this.selectEmpsParams).then(response => {
        this.employeesSelect = response.data.rows
      })
    },
    showBindPostToOrganization(row) { // 显示绑定岗位到组织机构 的弹窗
      this.showPostVisible = true
      this.postObjid = row.objid
    },
    bindPostToOrganization(data, node) { // 绑定岗位到组织机构
      commonApi('/organization/bind', 'post', {
        objid: this.postObjid, // objid是岗位objid,pup是组织机构的seqnr
        pid: data.code,
        vprozt: 100 }).then(response => {
        if (response.code === 1) {
          this.showPostVisible = false
          this.$message({
            message: `岗位绑定到 ${data.objec.stext} 成功`,
            type: 'success'
          })
          this.postList = this.postList.filter(item => {
            return item.objid !== this.postObjid
          })
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    unbindPostToOrganization(row) { // 从组织机构上解绑岗位
      this.$confirm(`确定要解绑岗位：${row.stext} ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        commonApi(`/organization/unbind`, 'post', { code: row.code, pid: this.nodeData.code }).then(response => {
          if (response.code === 1) {
            this.$message({
              message: `岗位（${row.stext}）解绑成功`,
              type: 'success',
              duration: 5000
            })
            this.postList = this.postList.filter(item => {
              return item.code !== row.code
            })
          }
        }).catch((err) => {
          console.log(err)
        })
      }).catch(() => {
      })
    },
    removePostToOrganization(row) { // 删除岗位
      this.$confirm(`确定要删除岗位：${row.stext} ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        commonApi(`/organization/remove/${row.code}`, 'get').then(response => {
          if (response.code === 1) {
            this.$message({
              message: `岗位（${row.stext}）删除成功`,
              type: 'success',
              duration: 5000
            })
            this.postList = this.postList.filter(item => item.code !== row.code)
          }
        }).catch((err) => {
          console.log(err)
        })
      }).catch(() => {
      })
    },
    showUnbindPost() { // 查找未绑定的岗位
      this.bindState = false
      this.postLoading = true
      commonApi('/organization/queryForUnbindOrganization', 'post', {
        otype: 'S'
      }).then(response => {
        if (response.code === 1) {
          this.postList = response.data
          this.postLoading = false
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    showAddPost() { // 岗位新增页面展示
      this.FormVisible = true
    },
    confirmPost(formName) { // 岗位新增 确定
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.bindState) {
            delete this.postInfo.otype
            this.postInfo.dimensionality = 'org'
            const data = { objec: this.postInfo, struc: { pid: this.nodeData.code }}
            commonApi('/organization/addPositionAndBinding', 'post', data).then(response => { // 增加岗位 并 绑定到组织机构
              if (response.code === 1) {
                for (const obj in this.postInfo) {
                  this.postInfo[obj] = null
                }
                this.switchChange()
                this.FormVisible = false
                this.$refs[formName].resetFields()
              }
            }).catch((err) => {
              console.log(err)
            })
          } else {
            this.postInfo.otype = 'S'
            const data = { objec: this.postInfo }
            commonApi('/organization/addOrganization', 'post', data).then(response => { // 增加岗位 未 绑定到组织机构
              if (response.code === 1) {
                for (const obj in this.postInfo) {
                  this.postInfo[obj] = null
                }
                this.showUnbindPost()
                this.FormVisible = false
                this.$refs[formName].resetFields()
              }
            }).catch((err) => {
              console.log(err)
            })
          }
        }
      })
    },
    cancelAdd(formName) { // 岗位新增取消
      this.FormVisible = false
      this.$refs[formName].resetFields()
    },
    postForbidden(row) { // 岗位激活/禁用
      commonApi('/organization/disable', 'post', {
        available: !row.available,
        code: row.code,
        otype: 'S' }).then(response => {
        if (response.code === 1) {
          const ava = row.available ? '禁用' : '激活'
          this.$message({ message: `${row.stext}:岗位${ava}完成`,
            type: 'success',
            duration: 5000
          })
          row.available = !row.available
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    rowClick(row) { // 点击行 触发
      this.empVisible = true
      this.getEmployeeFromPost(row)
      this.rowEmpData = row
    },
    getFrameworkTree() { // 组织机构树
      this.treeLoading = true
      commonApi('/organization/tree', 'get').then(response => {
        if (response.code === 1) {
          this.frameworkData = response.data
          this.getFrameworkDirectPost(this.frameworkData[0].nodes[0].objid)
          this.nodeData = this.frameworkData[0].nodes[0]
          this.getEmployees() // 获取员工数据
        }
        this.treeLoading = false
      }).catch((err) => {
        console.log(err)
      })
    },
    switchChange() {
      this.handleNodeClick(this.nodeData)
    },
    handleNodeClick(data, node) { // 点击节点触发事件
      this.bindState = true
      this.nodeData = data
      if (this.allChildEmployee.indexOf('直接') !== -1) {
        this.getFrameworkDirectPost(data.objid)
      } else {
        this.getFrameworkAllPost(data.objid)
      }
    },
    getFrameworkDirectPost(objId) { // 获取组织结构直接岗位
      this.postLoading = true
      commonApi(`/organization/queryDirectPositionByOrganization/${objId}`, 'get').then(response => {
        if (response.code === 1) {
          this.postList = response.data
          this.oldList = this.postList.map(v => v.code)
          this.newList = this.oldList.slice()
          this.$nextTick(() => {
            this.setSort()
          })
        }
        this.postLoading = false
      }).catch((err) => {
        console.log(err)
      })
    },
    getFrameworkAllPost(objId) { // 获取组织机构下所有岗位
      this.postLoading = true
      commonApi(`/organization/queryPositionByOrganization/${objId}`, 'get').then(response => {
        if (response.code === 1) {
          this.postList = response.data
          this.oldList = this.postList.map(v => v.code)
          this.newList = this.oldList.slice()
          this.$nextTick(() => {
            this.setSort()
          })
        }
        this.postLoading = false
      }).catch((err) => {
        console.log(err)
      })
    },
    getEmployeeFromPost(post) { // 从岗位中获取员工
      this.empLoading = true
      commonApi(`/organization/queryPersonByPosition/${post.objid}`, 'get').then(response => {
        if (response.code === 1) {
          this.employees = response.data
        }
        this.empLoading = false
      }).catch((err) => {
        console.log(err)
      })
    },
    setSort() {
      const el = document.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          dataTransfer.setData('Text', '')
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
        },
        onEnd: evt => {
          console.log(evt.oldIndex + '+' + evt.newIndex)
          const targetRow = this.postList.splice(evt.oldIndex, 1)[0]
          this.postList.splice(evt.newIndex, 0, targetRow)

          // for show the changes, you can delete in you code
          const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
          this.newList.splice(evt.newIndex, 0, tempIndex)

          this.dataSortChange(this.newList)
        }
      })
    },
    dataSortChange(newList) {
      commonApi('/organization/sortOrganization', 'post', newList).then(response => {
        if (response.code === 1) {
          console.log('成功')
        }
      })
    }
  }
}
</script>

<style>
  .sortable-ghost{
    opacity: .8;
    color: #fff!important;
    background: #42b983!important;
  }
</style>
<style scoped>
  .address-el-container{
    min-height: calc(100vh - 90px);
  }
  .address-tree{
    background-color: white;
    margin-right: 10px;
    padding: 10px;
  }
  .search-type{
    margin: 20px;
    display: flex;
    justify-content: space-around;
  }
</style>
